#ifndef _DB_MYSQLMGR_H_
#define _DB_MYSQLMGR_H_

#include <list>
using std::list;

#include "sysdef.h"
#include "thread.h"
#include "mutex.h"
#include "queue.h"
#include "singleton.h"

#include "mysql/include/mysql.h"

struct MysqlCmd
{
public:

    MysqlCmd(const char* sqltxt, const char* type = "sqlcmd");

    ~MysqlCmd();

    void CreateResInfo();

    int GetRowCount();
    int GetFieldsCount();
    int GetAffectedRows();

    const char* GetFieldName(int index);;
    const char* GetRowData(int rowindex, int columindex);

    bool _result;
    string _type;
    string _sqltxt;

    int _mysqlrowcount;
    int _mysqlfieldcount;
    int _mysqlaffectedrows;
    MYSQL_RES* _mysqlres;
    MYSQL_ROW* _mysqlrows;
};

struct SqlInfo
{
    SqlInfo& operator=(const SqlInfo& r)
    {
        if(&r == this) return *this;

        _port = r._port; _ip = r._ip; _username = r._username; _userpwd = r._userpwd; _dbname = r._dbname;

        return *this;
    }

    ushort _port;
    string _ip;
    string _username;
    string _userpwd;
    string _dbname;
};

class CLog;

typedef void mysql_callback_func(MysqlCmd* outcmd);

class CCowMysql
{
    friend THREAD_HANDLE(cow_mysql_thread, param);

public:

    CCowMysql(SqlInfo& sqlinfo, mysql_callback_func* callback = NULL);

    ~CCowMysql();

    bool Start();
    
    void SyncWork(MysqlCmd& incmd);

private:

    bool Connect();

    void WorkThread();

    CLog* m_log;

    bool    m_isrun;

    MYSQL*  m_pmysql;

    CThread m_thread;

    SqlInfo m_sqlinfo;
    
    uint m_excutetime;

    mysql_callback_func* m_callback;

    CQueue<MysqlCmd*> m_sqlincmds;
    CQueue<MysqlCmd*> m_sqloutcmds;
};

#endif //_DB_MYSQLMGR_H_
